package cn.wx.basic.controller;

import cn.wx.basic.util.FastDfsUtils;
import cn.wx.basic.util.JsonResult;
import org.apache.tomcat.jni.Multicast;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /*
    * 上传文件
    * */
    @PostMapping
    public JsonResult upload(@RequestPart(value ="file",required = true ) MultipartFile file){
//
//        try {
//            //获取当前的文件名字
//            String originalFilename = file.getOriginalFilename();
//            //截取后缀名
//            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")+1); //jpg
//            //调用工具类的上传方法
//            // 把logo路径传给前端
//            String log = FastDfsUtils.upload(file.getBytes(), substring);
//            //返回json
//            return JsonResult.me().setResultObj(log);
//        }catch (Exception e ){
//            e.printStackTrace();
//            return JsonResult.me().setMsg("上传失败");
//        }



        try {
            String originalFilenam = file.getOriginalFilename(); // 404.png
            String extName = originalFilenam.substring(originalFilenam.lastIndexOf(".")+1);
            ////  /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String filename = FastDfsUtils.upload(file.getBytes(), extName);
            //将上传之后的名字响应给 前端
            return JsonResult.me().setResultObj(filename);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("上传失败");
        }
    }
    /*
    * 删除文件
    *
    * */
    @DeleteMapping()
    public JsonResult del(@RequestParam(value = "path", required = true)   String path){

        try {
            //传过来的    /group1/M00/00/F0/CgAIC2LdE8OAT5l0AADdj5ZcvfY694.jpg
            String substring = path.substring(1); //   group1/M00/00/F0/CgAIC2LdE8OAT5l0AADdj5ZcvfY694.jpg
            String substring1 = substring.substring(0, substring.indexOf("/")); //   group1
            String substring2 = substring.substring(substring.indexOf("/")+1); //  M00/00/F0/CgAIC2LdE8OAT5l0AADdj5ZcvfY694.jpg

            FastDfsUtils.delete(substring1,substring2);
            return JsonResult.me();

        }catch (Exception e){
            e.printStackTrace();
            return  JsonResult.me().setMsg("删除失败");
        }
    }

}
